package com.zc.util;


import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * OkHttp封装,调用示例OkHttpUtil.postJson(...)
 * Created by zhangcheng01 on 2018/3/15 12:56.
 */
public class OkHttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);

    private static final byte[] LOCKER = new byte[0];
    private static volatile OkHttpClient okHttpClient;

    private OkHttpUtil() {

    }

    private static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (LOCKER) {
                if (okHttpClient == null) {
                    OkHttpClient.Builder ClientBuilder = new OkHttpClient.Builder();
                    ClientBuilder.readTimeout(30, TimeUnit.SECONDS);//读取超时
                    ClientBuilder.connectTimeout(30, TimeUnit.SECONDS);//连接超时
                    ClientBuilder.writeTimeout(60, TimeUnit.SECONDS);//写入超时
                    okHttpClient = ClientBuilder.build();
                }
            }
        }
        return okHttpClient;
    }

    /**
     * 发送get请求
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static Response get(String url) throws IOException {
        logger.debug("请求url:{}", url);

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute();

        logger.debug("{}请求处理结果:{}", url, response);

        return response;

    }

    /**
     * 发送get请求,带参数
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static Response get(String url, Map<String, String> params) throws IOException {
        logger.debug("请求url:{}", url);

        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            //追加表单信息
            urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
        }

        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();

        Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute();

        logger.debug("{}请求处理结果:{}", url, response);

        return response;

    }


    /**
     * 发送json请求
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static Response postJson(String url, String json) throws IOException {
        logger.debug("请求url:{},请求体:{}", url, json);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式，

        RequestBody requestBody = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute();

        logger.debug("{}请求处理结果:{}", url, response);

        return response;

    }

    /**
     * 发送form表单post请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static Response post(String url, Map<String, String> params) throws IOException {
        logger.debug("请求地址:{};", url);
        //创建一个FormBody.Builder
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            //追加表单信息
            builder.add(entry.getKey(), entry.getValue());
        }
        //生成表单实体对象
        RequestBody formBody = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute();

        logger.debug("{}请求处理结果:{}", url, response);

        return response;

    }


    /**
     * 发送form表单post请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static Response postWithHeader(String url, Map<String, String> params, String... headers) throws IOException {
        logger.debug("请求url:{};", url);
        //创建一个FormBody.Builder
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            //追加表单信息
            builder.add(entry.getKey(), entry.getValue());
        }
        //生成表单实体对象
        RequestBody formBody = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(headers))
                .post(formBody)
                .build();
        Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute();

        logger.debug("{}请求处理结果:{}", url, response);

        return response;
    }

    /**
     * 发送form表单post请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static Response postFile(String url, String fileName, File file, Map<String, String> params) throws IOException {
        logger.debug("请求url:{};", url);

        MultipartBody.Builder builder = new MultipartBody.Builder();

        builder.addFormDataPart(fileName, fileName, RequestBody.create(MediaType.parse("application/octet-stream"), file));

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                //追加表单信息
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }

        }

        MultipartBody multipartBody = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(multipartBody)
                .build();
        Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute();

        logger.debug("{}请求处理结果:{}", url, response);

        return response;
    }
}
